package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.squareup.picasso.Picasso;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.ImageBean;
import com.zhongjian.technologycal.mall.bean.UserInfoBean;
import com.zhongjian.technologycal.mall.net.ApiRetrofitClient;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/11/16.
 * 个人中心用户信息
 */

public class PersonalCenterInfoActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.system_ll_setting_userid)
    TextView system_ll_setting_userid;
    @BindView(R.id.center_tv_nickname)
    TextView center_tv_nickname;
    @BindView(R.id.pensonal_iv_img)
    CircleImageView pensonal_iv_img;
    @BindView(R.id.system_tv_setting_person)
    TextView system_tv_setting_person;
    @BindView(R.id.system_ll_setting_person)
    LinearLayout system_ll_setting_person;
    @BindView(R.id.system_tv_setting_phone)
    TextView system_tv_setting_phone;
    @BindView(R.id.next_img)
    ImageView next_img;
    private String upLoadImgPath = null;
    private static final int IMAGE_PICKER = 5;
    private static final int REQUEST_CODE_SELECT = 6;
    private Dialog picChooseDialog = null;
    private String telphone;
    private String nickName;

    @Override
    protected void beforeInit() {
        super.beforeInit();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.border_color), 0);
        tv_main_title.setText("个人中心");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_personal_center_info;
    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    @OnClick(R.id.system_ll_setting_heading)
    public void onClickSettingHeading() {
//        ActivityCompat.requestPermissions(this,
//                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                MY_PERMISSIONS_REQUEST_CALL_PHONE2);
        picChooseDialog = new Dialog(this, R.style.pic_choose_dialog_progress);
        View view = LayoutInflater.from(getBaseContext()).inflate(
                R.layout.pic_choose_dialog, null);
        TextView choose_tv_photo1 = (TextView) view
                .findViewById(R.id.choose_tv_photo1);
        TextView choose_tv_photo2 = (TextView) view
                .findViewById(R.id.choose_tv_photo2);
        TextView choose_tv_cancel = (TextView) view
                .findViewById(R.id.choose_tv_cancel1);
        /**
         * 相册选择图片上传
         */
        choose_tv_photo1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                picChooseDialog.dismiss();
            }
        });
        /**
         * 拍照上传
         */
        choose_tv_photo2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                picChooseDialog.dismiss();
            }
        });
        /**
         * 取消
         */
        choose_tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                picChooseDialog.dismiss();
            }
        });
        Window window = picChooseDialog.getWindow();
        window.setContentView(view);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(android.view.WindowManager.LayoutParams.MATCH_PARENT,
                android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        window.setWindowAnimations(R.style.popupWindowAnimation);
        picChooseDialog.setCanceledOnTouchOutside(true);
        picChooseDialog.show();
    }

    /**
     * 设置昵称
     */
    @OnClick(R.id.system_ll_setting_nickname)
    public void onClickSystemSettingNickname() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), SettingNickNameActivity.class);
        intent.putExtra("nickName", nickName);
        startActivity(intent);
    }

    /**
     * 更换账号
     */
    @OnClick(R.id.system_ll_setting_phone)
    public void onClickSystemSettingChangePhone() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), ChangeTelPhoneActivity.class);
        intent.putExtra("telphone", telphone);
        startActivity(intent);
    }

    @Override
    public void initPresenter() {
        initViewPersonInfo();
    }

    /**
     * 获取用户信息
     */
    private void initViewPersonInfo() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).getUrlRequestCenterData(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Gson gson = new Gson();
                            UserInfoBean userInfoBean = gson.fromJson(responseBody.string(), UserInfoBean.class);
                            if (userInfoBean.getError_code() == 0) {
                                system_ll_setting_userid.setText("" + userInfoBean.getData().getPersonDataMap().getSysID());
//                                Glide.with(getBaseContext()).load(BaseContacts.BASE_URL + userInfoBean.getData()
//                                        .getPersonDataMap().getHeadPhoto()).into(pensonal_iv_img);

                                Picasso.get().load(BaseContacts.BASE_URL + userInfoBean.getData()
                                        .getPersonDataMap().getHeadPhoto())
                                        .resize(200,250).into(pensonal_iv_img);
                                center_tv_nickname.setText("" + userInfoBean.getData().getPersonDataMap().getNickName());
                                nickName = userInfoBean.getData().getPersonDataMap().getNickName();
                                telphone = userInfoBean.getData().getPersonDataMap().getUserName();
                                String newPhone = telphone.substring(0, 3) + "****" + telphone.substring(7, telphone.length());
                                system_tv_setting_phone.setText("" + newPhone);
                                if (TextUtils.isEmpty(
                                        String.valueOf(userInfoBean.getData().getPersonDataMap().getBeInviteCode()))
                                        || userInfoBean.getData().getPersonDataMap().getBeInviteCode() == 0) {
                                    system_ll_setting_person.setClickable(true);
                                    next_img.setVisibility(View.VISIBLE);
                                } else {
                                    system_ll_setting_person.setClickable(false);
                                    next_img.setVisibility(View.GONE);
                                    if (userInfoBean.getData().getPersonDataMap().getBeInviteCode() == 0) {
                                        system_tv_setting_person.setText("");
                                    } else {
                                        next_img.setVisibility(View.GONE);
                                        system_tv_setting_person.setText("" + userInfoBean.getData().getPersonDataMap().getBeInviteCode());
                                    }

                                }
                            } else if (userInfoBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else {
                                ToastUitl.showShort(userInfoBean.getError_message());
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    /**
     * 设置推荐人
     */
    @OnClick(R.id.system_ll_setting_person)
    public void onClickSettingPerson() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), SettingPersonNumActivity.class);
        startActivity(intent);
    }

    /**
     * 上传图片
     *
     * @param path
     */
    private void requestUploadToImage(String path) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        File file = new File(path);
        final RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        ApiRetrofitClient.getInstance(getBaseContext()).postUrlRequestUploadPhoto(body,
                UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(PersonalCenterInfoActivity.this, "上传图片中", true);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                upLoadImgPath = baseBean.getData().toString();
                                requestToImage(baseBean.getData().toString());
                                ToastUitl.showShort(baseBean.getError_message());
                            } else if (baseBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);

                            } else {
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }


    /**
     * 更新头像
     *
     * @param path
     */
    private void requestToImage(String path) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;

        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestUploading(UserUtils.getUserToken(),
                path,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(PersonalCenterInfoActivity.this);

                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            ImageBean imageBean = gson.fromJson(responseBody.string(), ImageBean.class);
                            if (imageBean.getError_code() == 0) {
//                                Glide.with(getBaseContext()).load(BaseContacts.BASE_URL + upLoadImgPath
//                                ).into(pensonal_iv_img);
                                Picasso.get().load(BaseContacts.BASE_URL + upLoadImgPath)
                                        .resize(200,250).into(pensonal_iv_img);
                            } else if (imageBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else {
                                ToastUitl.showShort(imageBean.getError_message());
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewPersonInfo();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            // camear 权限回调
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_PICKER);
            } else {
                //用户拒绝权限
                ToastUitl.showShort("没有权限，请先授权！");
            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String imgpath = images.get(0).path;
                requestUploadToImage(imgpath);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images1 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String imgpath = images1.get(0).path;
                requestUploadToImage(imgpath);
            } else {
                ToastUitl.showShort("没有图片数据～");
            }
        }

    }
}
